package com.identify.identifydrawings;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.ObjectKey;
import com.google.gson.Gson;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.identify.identifydrawings.netUtils.JsonUtils;
import com.identify.identifydrawings.netUtils.Url;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Search extends AppCompatActivity {

    // 申请权限的集合，同时要在AndroidManifest.xml中申请，Android 6以上需要动态申请权限
    String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();
    public static List<String> list=MainActivity.filedata;
    RecyclerView recyclerView;
    EditText tvCode;
    PhotoView photoView;
    File f;
    CutImageAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        tvCode = findViewById(R.id.tvCode);
        photoView = findViewById(R.id.imgSearch);
        //initList();
        recyclerView = (RecyclerView) findViewById(R.id.recycler_cutimage);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
//        detectcut();
        Log.e("TAG", "filedata=" + MainActivity.filedata);
        Log.e("TAG", "Clearfiledata=" + list);
        adapter = new CutImageAdapter(list);
        adapter.setOnItemClickLitener(new CutImageAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(Search.this,"这是条目"+list.get(position),Toast.LENGTH_LONG).show();
                conut=0;
                yuancut.clear();
                cutyuanadress(list.get(position));

                //String searchstr = detectText(cut);
                //String searchstr = yuancut.get(0);
//                setVertifyResult(searchstr);
                //Log.e("TAG", "searchstr=" + searchstr);

            }
        });
        recyclerView.setAdapter(adapter);
        // 启用图片缩放功能
        photoView.enable();
        Album.initialize(AlbumConfig.newBuilder(this)
                .setAlbumLoader(new MediaLoader())
                .build());
        initOcr();
    }

    private String path1;
    public static int conut;
    public static List<String> yuancut=new ArrayList<>();
    private void cutyuanadress(String pathstr) {
        //List<String> yuancut=new ArrayList<>();
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(Search.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        //未授予的权限为空，表示都授予了
        if (mPermissionList.isEmpty()) {
            //读取根目录下的一张图片
            path1 = pathstr;
            Log.e("TAG", "pathstr=" + path1);
            boolean fileExist = fileIsExists(path1);
            Log.e("TAG", "fileExist=" + fileExist);
            if (fileExist) {
                //Toast.makeText(MainActivity.this,"开始上传"+f.getAbsolutePath(),Toast.LENGTH_LONG).show();
                try {
                    //上传图片
                    ImageUploadcutyuan.run(f, new ResponseListener() {
                        @Override
                        public void onResonse(final String response) {
                            Log.e("TAG","MainActivity response="+response);//nishuo
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (TextUtils.isEmpty(response)) {
                                        Toast.makeText(Search.this, "没有返回", Toast.LENGTH_SHORT).show();
                                    } else{
                                        File file = new File(response);//定义一个file对象，用来初始化FileReader
                                        FileReader reader = null;//定义一个fileReader对象，用来初始化BufferedReader
                                        try {
                                            reader = new FileReader(file);
                                            BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
                                            StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
                                            String s = "";
                                            while ((s = bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
                                                sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
                                                System.out.println(s);
                                            }
                                            bReader.close();
                                            String str = sb.toString();
                                            Log.e("TAG", "String=" + str);
//gson
                                            Gson gson = new Gson();
                                            TestBean data = gson.fromJson(str, TestBean.class);
                                            List<String> pathcutyuan = data.getPath();
                                            conut =pathcutyuan.size();
                                            for (int i = 0; i < pathcutyuan.size(); i++) {
                                                Log.e("TAG", "Stringpathcut=" + pathcutyuan.get(i));
                                                String cut=pathcutyuan.get(i);
                                                ImageUploadyuanAdress.run(cut, new ResponseListener() {
                                                    @Override
                                                    public void onResonse(final String response) {
                                                        Log.e("TAG","MainActivity response="+response);//nishuo
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                if (TextUtils.isEmpty(response)) {
                                                                    Toast.makeText(Search.this, "没有返回", Toast.LENGTH_SHORT).show();
                                                                } else {
                                                                    //百度OCR
                                                                    vertify(response);
                                                                    //detectText(response);
                                                                }
                                                            }
                                                        });

                                                    }
                                                    @Override
                                                    public void onFail(String code, String msg) {

                                                    }
                                                });
                                            }
//                                            runOnUiThread(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    Log.e("TAG","yuancut1="+yuancut);
//                                                    String restr = yuancut.get(0) + "-" + yuancut.get(1) + ".png";
//                                                    Log.e("TAG","restr="+restr);
//                                                    tvCode.setText(restr);
//                                                }
//                                            });



                                        } catch (FileNotFoundException e) {
                                            e.printStackTrace();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }

                                }

                            });

                        }

                        @Override
                        public void onFail(String code, String msg) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //readImg(showImg);
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
            ActivityCompat.requestPermissions(Search.this, permissions, 1);
        }
    }
    //检测的图片路径是否存在
    public boolean fileIsExists(String strFile) {
        try {
            f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private boolean hasGotToken;//是否設置orc成功
    /**
     * 初始化 orc
     */
    private void initOcr() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
                Log.e("TAG  AK，SK方式获取token成功", "token=" + token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Log.e("TAG  AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(), "4p2Xng7gIhFRU9nhUGjZWd2p", "w31GOoyvs5ArTp2VTsEseBfqpGspllKy");
    }
    //识别算法tess-two
    public void detectText(String pathstr) {
        conut--;
        Log.e("TAG", "tesspathstr=" + pathstr);
            Bitmap bitmap=BitmapFactory.decodeStream(getClass().getResourceAsStream(pathstr));
        Log.e("TAG", "bitmap=" + bitmap);
            TessBaseAPI tessBaseAPI = new TessBaseAPI();
            String pathtess = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tesseract/tessdata/"; //训练数据路径

            tessBaseAPI.setDebug(true);
            tessBaseAPI.init(pathtess, "eng"); //eng为识别语言
            tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789()"); // 识别白名单
            tessBaseAPI.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!@#$%^&*_+=-[]}{;:'\"\\|~`,./<>?"); // 识别黑名单
            tessBaseAPI.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO_OSD);//设置识别模式

            tessBaseAPI.setImage(bitmap); //设置需要识别图片的bitmap
            String inspection = tessBaseAPI.getUTF8Text();
        Log.e("TAG", "inspection=" + inspection);
            tessBaseAPI.end();
        yuancut.add(inspection);
        //Log.e("TAG", "zimushuzi: " + str);
        Log.e("TAG", "yuancut=" + yuancut);
        if (conut==0){
            setVertifyResult();
        }


    }
    //int m=0;
    //识别算法
    public void vertify(String path) {
        //操作

        final StringBuilder resultStr = new StringBuilder();
        RecognizeService.recAccurateBasic(this, path,
                new RecognizeService.ServiceListener() {
                    @Override
                    public void onResult(final String result) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e("TAG", "recAccurateBasic  result=" + result);
                                VertifyData vertifyData = JsonUtils.parseJsonToBean(result, VertifyData.class);
                                Log.e("TAG", "recAccurateBasic  vertifyData=" + vertifyData);
                                if (vertifyData == null || vertifyData.getWords_result() == null || vertifyData.getWords_result().size() <= 0) {
                                    //setVertifyResult(resultStr.toString());
                                } else {
                                    conut--;
                                    Log.e("TAG", "conutzhi=" + conut);
                                    for (int i = 0; i < vertifyData.getWords_result().size(); i++) {
                                        //只留得到的字母和数字
                                        resultStr.append(vertifyData.getWords_result().get(i).getWords().replaceAll("[^a-zA-Z0-9()一二三四五六七八九十]", ""));
                                    }
                                    yuancut.add(resultStr.toString());
                                    //Log.e("TAG", "zimushuzi: " + str);
                                    Log.e("TAG", "yuancut=" + yuancut);
                                    if (conut==0){
                                        setVertifyResult();
                                    }


                                }
                            }

                        });
                }

        //Log.e("TAG", "resultStr: " + resultStr.toString());
        //return resultStr.toString();
    });
    }

    private void setVertifyResult() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                List<String> vertify=yuancut;
                if (vertify.size()==0) {
                    Log.e("TAG", "识别失败");
                    tvCode.setText("识别失败,请手动输入");
                } else {
                    Log.e("TAG", "识别成功");
                    if (vertify.get(0).length()>vertify.get(1).length()){
                        tvCode.setText(vertify.get(0)+"-"+vertify.get(1)+".png");
                    }else {
                        tvCode.setText(vertify.get(1)+"-"+vertify.get(0)+".png");
                    }

                }
            }
        });

    }
    //搜索
    public void searchImg(View view) {
        //oss
        //返回图片
        //imgSearch
        String text = tvCode.getText().toString();
        getImage(text);
    }

    //獲取token
    private String getImage(String e_account) {
        String results = null;
        HashMap map = new HashMap();
        //?Action=AssumeRole&&RoleArn=acs:ram::1843770436407740:role/AliyunOSSTokenGeneratorRole&RoleSessionName=banyaolian
        map.put("e_account", e_account);

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .get()
                .url(Url.getFileFormNet + "?e_account=" + e_account)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", "onFailure: " + e.getMessage());
                ;

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //  String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LungFile";
                Log.e("TAG", "response=" + response);

                int code = response.code();
                if (code != 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(Search.this, "key值不对", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
                String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/eeee";

                final File file = new File(dirName);
                if (!file.exists()) {
                    file.mkdir();
                }

                File file1 = new File(dirName + "/" + "facenew1.png");
                if (response != null) {
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(file1);
                    int len = 0;
                    byte[] buffer = new byte[2048];
                    while (-1 != (len = is.read(buffer))) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                }
                setImg(file1);
            }
        });
        return results;
    }

    private void setImg(final File file) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Glide.with(Search.this)
                        .load(file.getAbsolutePath())
                        .into(photoView);
            }
        });
        // 获取图片信息
        //  Info info = photoView.getInfo();
// 从普通的ImageView中获取Info
        //Info info = PhotoView.getImageViewInfo(ImageView);
// 从一张图片信息变化到现在的图片，用于图片点击后放大浏览，具体使用可以参照demo的使用
        //photoView.animaFrom(info);
// 从现在的图片变化到所给定的图片信息，用于图片放大后点击缩小到原来的位置，具体使用可以参照demo的使用
//        photoView.animaTo(info,new Runnable() {
//            @Override
//            public void run() {
//                //动画完成监听
//            }
//        });
// 获取/设置 动画持续时间
        //photoView.setAnimaDuring(1000);
        int d = photoView.getAnimaDuring();
// 获取/设置 最大缩放倍数
        // photoView.setMaxScale(2);
        //  float maxScale = photoView.getMaxScale();
// 设置动画的插入器
        // photoView.setInterpolator(Interpolator interpolator);


    }
}
